package jpavlich.cardsorter;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import com.thoughtworks.xstream.XStream;

import jpavlich.cardsorter.action.Experiment;

public class Persistence {

	public static final File EXPERIMENTS_PATH = new File("./experimentos");
	private static final String EXPERIMENT_ACTIONS_FILE = "actions.cardSorter";
	private File selectedExpDir;
	private File experimentFile;
	private XStream xstream = new XStream();

	public Persistence(String experimentID) {
		init(new File(EXPERIMENTS_PATH, experimentID));
	}

	public Persistence(File selectedExpDir) {
		init(selectedExpDir);
	}

	public void init(File selectedExpDir) {
		this.selectedExpDir = selectedExpDir;
		if (!selectedExpDir.exists()) {
			selectedExpDir.mkdirs();
		}
		experimentFile = new File(selectedExpDir, EXPERIMENT_ACTIONS_FILE);
	}

//	public void save(Experiment actionManager) throws Exception {
//		FileOutputStream fileOut = new FileOutputStream(actionsFile);
//		ObjectOutputStream out = new ObjectOutputStream(fileOut);
//		out.writeObject(actionManager);
//		out.close();
//		fileOut.close();
//	}
//
//	public Experiment load() throws Exception {
//		FileInputStream fileIn = new FileInputStream(actionsFile);
//		ObjectInputStream in = new ObjectInputStream(fileIn);
//		Experiment exp = (Experiment) in.readObject();
//		in.close();
//		fileIn.close();
//		exp.setPersistence(this);
//		return exp;
//	}
	
	public void save(Experiment exp) throws Exception {
		FileOutputStream out = new FileOutputStream(experimentFile);
		xstream.toXML(exp, out);
		out.flush();
		out.close();
	}
	
	public Experiment load() throws Exception {
		FileInputStream fileIn = new FileInputStream(experimentFile);
		System.out.println("Opening file " + experimentFile.getAbsolutePath());
		Experiment exp = (Experiment) xstream.fromXML(fileIn);
		exp.setPersistence(this);
		fileIn.close();
		return exp;
	}

	public File getSelectedExpDir() {
		return selectedExpDir;
	}

}
